package chaos.infinity.mixin.Sandpile;

//

import net.minecraft.block.BlockState;
import net.minecraft.block.FallingBlock;
import net.minecraft.entity.FallingBlockEntity;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.util.math.random.Random;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.*;

import static net.minecraft.util.math.Direction.*;

@Mixin(FallingBlock.class)
public abstract class Sandpile_Mixin {
    @Shadow
    public static boolean canFallThrough(BlockState state) { return false; }

    @Shadow
    protected void configureFallingBlockEntity(FallingBlockEntity entity) { }

    // 在原版检测逻辑之后注入（TAIL）
    @Inject(method = "scheduledTick",
            at = @At(value = "HEAD"))
    private void scheduledTick_Mixin(BlockState state, ServerWorld world, BlockPos pos, Random random, CallbackInfo ci) {
        canFallSide(state, world, pos);

    }

    private void canFallSide(BlockState state, ServerWorld world, BlockPos pos) {
        // 原版检测下方是否可下落
        if (FallingBlock.canFallThrough(world.getBlockState(pos.down()))) return;

        List<Direction> directions = Arrays.asList(Direction.EAST, WEST, NORTH, SOUTH);
        Collections.shuffle(directions);

        for (Direction dir : directions) {
            BlockPos targetSide = pos.offset(dir);
            BlockPos targetBelow = targetSide.down();

            if (isPassable(world, targetSide) &&
                    isPassable(world, targetBelow)) {

                //先移出原来的方块
                world.removeBlock(pos, false);
                //再在指定方向生成下落实体
                FallingBlockEntity fallingBlockEntity = FallingBlockEntity.spawnFromBlock(world, targetSide, state);

                break;
            }
        }
    }

    // 兼容流体检测（包含网页1提到的流体更新机制）
    private boolean isPassable(World world, BlockPos pos) {
        BlockState state = world.getBlockState(pos);
        return state.isAir() || state.getFluidState().isStill();
    }
}